//
//  DataManager.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/12/7.
//

import Foundation
import CoreData

class DataManager: NSObject,ObservableObject {
    static let shared = DataManager()

    lazy var persistentContainer : NSPersistentContainer = {
        let container : NSPersistentContainer = NSPersistentContainer(name: "JiaoZiTaxi")
        container.loadPersistentStores(completionHandler:  { storeDescription, error in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error),\(error.userInfo)")
            }
        })
        return container
    }()

   @Published var carOrders : [TaxiOrder] = [TaxiOrder]()

    func save() {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(error),\(nserror.userInfo)")
            }
        }
    }

    func addOrder(order:TaxiOrder) {
        carOrders.append(order)
        self.save()
    }

    func checkOrderExist(orderNo:String) -> Bool {
        let fetchRequest : NSFetchRequest<TaxiOrder> = TaxiOrder.fetchRequest()
        fetchRequest.fetchLimit = 1
        let predicate = NSPredicate(format: "orderNo == %@",orderNo)
        fetchRequest.predicate = predicate
        do {
            let orders = try DataManager.shared.persistentContainer.viewContext.fetch(fetchRequest)
            if orders.count == 1 {
                return true
            } else {
                return false
            }
        } catch {
            print("fetch data error:\(error)")
            return false
        }
    }
}
